package com.wl156.activities;

import java.io.IOException;

import org.ksoap2.serialization.SoapPrimitive;
import org.xmlpull.v1.XmlPullParserException;

import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

import com.wl156.BaseActivity;
import com.wl156.MyApp;
import com.wl156.R;
import com.wl156.model.Certificate;
import com.wl156.model.WebServiceClient;

public class ChangePassword extends BaseActivity implements OnClickListener {

	private WebServiceClient mWebServiceClient;
	private Certificate mCertificate;

	private EditText mOld;
	private EditText mNew;
	private EditText mNewConfirm;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.act_change_password);

		mWebServiceClient = new WebServiceClient(this);
		mCertificate = ((MyApp) getApplication()).getCertificateFromXml();

		findViewById(R.id.confirm).setOnClickListener(this);
		mOld = (EditText) findViewById(R.id.oldPassword);
		mNew = (EditText) findViewById(R.id.newPassword);
		mNewConfirm = (EditText) findViewById(R.id.newPasswordConfirm);
	}

	@Override
	public void onClick(View v) {
		final String old = mOld.getText().toString();
		final String newPwd = mNew.getText().toString();
		String newPwdConfirm = mNewConfirm.getText().toString();

		if (TextUtils.isEmpty(old) || TextUtils.isEmpty(newPwd)
				|| TextUtils.isEmpty(newPwdConfirm)) {
			Toast.makeText(this, "请输入相应字段", Toast.LENGTH_SHORT).show();
			return;
		}

		if (!newPwd.equals(newPwdConfirm)) {
			Toast.makeText(this, "两次输入密码不同", Toast.LENGTH_SHORT).show();
			return;
		}

		new AsyncTask<Void, Void, Object>() {

			protected void onPostExecute(Object result) {
				if (result instanceof Exception) {
					Exception e = (Exception) result;
					Toast.makeText(ChangePassword.this, "网络异常，请稍后再试",
							Toast.LENGTH_SHORT).show();
				} else if (result instanceof SoapPrimitive) {
					SoapPrimitive sp = (SoapPrimitive) result;

					Toast.makeText(ChangePassword.this, sp.toString(),
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(ChangePassword.this, "更新成功",
							Toast.LENGTH_SHORT).show();
				}
			};

			@Override
			protected Object doInBackground(Void... params) {
				try {
					return mWebServiceClient.common_ModifyPassword(
							mCertificate, newPwd, old);
				} catch (IOException e) {
					e.printStackTrace();
					return e;
				} catch (XmlPullParserException e) {
					e.printStackTrace();
					return e;
				}
			}

		}.execute();
	}
}
